<template>
  <div class="write-rebate">
    <!-- 操作結果提示 -->
    <msg v-if="doneShow" class="done-msg" :icon="doneIcon">
      <template slot="buttons">
        <router-link class="success-btn" v-if="doneIcon === 'success'" :to="{ name: 'InitiateApplication'}">
          返回首页
        </router-link>
        <a class="success-btn" v-else @click="closeDoneInfo">返回合作申请</a>
      </template>
      <template slot="description">
        <p class="title">{{doneTitle}}</p>
        <p>{{doneMsg}}</p>
      </template>
    </msg>
    <div class="scroll-box" v-show="!doneShow">
      <!-- 文本域+照片選擇組件 -->
      <my-rebate-textarea ref="rebateTextarea"></my-rebate-textarea>
      <!-- 審批人 -->
      <!-- <my-approver ref="approver"></my-approver> -->
      <!-- 抄送人 -->
      <my-make-copy ref="makeCopy" :makeCopyParams="makeCopyParams"></my-make-copy>
    </div>
    <!-- 底部組件 -->
    <my-bottom-submit v-if="!doneShow" @click.native="applySubmit"></my-bottom-submit>
    <!-- 加载中 -->
    <loading class="loading-mask" :show="loadingShow" text="加载中..."></loading>
    <!-- 提示彈窗 -->
    <div v-transfer-dom>
      <confirm v-model="turndownShow"
       class="turndown-confirm" title="提示" confirm-text="确认" :show-cancel-button="false">
        <p>{{turndownText}}</p>
      </confirm>
    </div>
  </div>
</template>

<script>
  import RebateTextarea from '@/components/ApplyWrite/RebateTextarea.vue';
  // import Approver from '@/components/ApplyWrite/Approver.vue';
  import MakeCopy from '@/components/ApplyWrite/MakeCopy.vue';
  import BottomSubmit from '@/components/Bottom/BottomSubmit.vue';
  import { Msg, Loading, Confirm, TransferDom } from 'vux';
  import qs from 'qs';
  export default {
    name: 'WriteRebate',
    data () {
      return {
        doneIcon: '',
        doneTitle: '',
        doneMsg: '',
        doneShow: false,
        loadingShow: false,
        required: ['CompanyName', 'GuestName', 'TransactionAddress'],
        turndownShow: false,
        turndownText: '',
        makeCopyParams: []
      };
    },
    directives: {
      TransferDom
    },
    components: {
      Loading,
      Msg,
      Confirm,
      'my-rebate-textarea': RebateTextarea,
      // 'my-approver': Approver,
      'my-make-copy': MakeCopy,
      'my-bottom-submit': BottomSubmit
    },
    created () {
    },
    mounted () {
      this.pageInit();
      if (this.$refs.makeCopy.resultList.length === 0) {
        this.$refs.makeCopy.resultList = this.makeCopyParams;
      }
    },
    watch: {
      $route (to, from) {
        setTimeout(() => {
          this.loadingShow = false;
          this.changeDoneInfo(false);
        }, 500);
        this.pageInit(to, from);
      }
    },
    methods: {
      // 頁面初始化
      pageInit: function (to, from) {
        let isHomeToThisPage;
        if (to && from) {
          isHomeToThisPage = from.name === 'InitiateApplication' && this.$route.name === 'WriteRebate';
        }
        let isReApplyToThisPage = this.$route.query.applyInfo;
        if (isHomeToThisPage) {
          // this.$refs.rebateTextarea.reasonText = '';
          this.$refs.rebateTextarea.companyName = '';       // 合作公司名稱 【提交】
          this.$refs.rebateTextarea.guestName = '';          // 客人名稱 【提交】
          this.$refs.rebateTextarea.transactionAddress = '';  // 成交地址 【提交】
          this.$refs.rebateTextarea.imagesList = [];
          this.$refs.rebateTextarea.previewerImagesList = [];
          this.$refs.rebateTextarea.imagesUploadList = [];
          // this.$refs.makeCopy.resultList = [];
          // this.makeCopyParams = this.getDefaultMakeCopy();
          this.$refs.rebateTextarea.reApplyReasonShow = false;
          this.required.pop();
        } else if (isReApplyToThisPage && this.$route.name === 'WriteRebate') {
          let params = JSON.parse(this.$route.query.applyInfo);
          // this.makeCopyParams = this.getDefaultMakeCopy();
          // let copiers = params.Copiers.slice(1, params.Copiers.length);
          let copiers = params.Copiers;
          if (copiers.length !== 0) {
            this.getReApplyMakeCopy(copiers);
          }
          this.$refs.rebateTextarea.companyName = params.Content.CompanyName;
          this.$refs.rebateTextarea.guestName = params.Content.GuestName;
          this.$refs.rebateTextarea.transactionAddress = params.Content.TransactionAddress;
          this.$refs.rebateTextarea.imagesList = params.Content.Images;
          this.$refs.rebateTextarea.reApplyReasonShow = true;
          this.$refs.rebateTextarea.reApplyReason = '';
          this.required.push('ReApplyReason');
        } else {
          this.makeCopyParams = this.getDefaultMakeCopy();
        }
      },
      // 提交事件
      applySubmit: function () {
        if (this.loadingShow) {
          return false;
        }
        let ContentData = {
          // Content: this.$refs.rebateTextarea.reasonText,
          Images: this.$refs.rebateTextarea.imagesList,
          CompanyName: this.$refs.rebateTextarea.companyName,
          GuestName: this.$refs.rebateTextarea.guestName,
          TransactionAddress: this.$refs.rebateTextarea.transactionAddress
        };
        if (this.$refs.rebateTextarea.reApplyReasonShow === true) {
          ContentData.ReApplyReason = this.$refs.rebateTextarea.reApplyReason;
        }
        let postData = {
          data: {
            Type: 2,
            CreatedStaffNo: this.getUserInfo().StaffNo,
            Copiers: this.parseCopiers(),
            Content: JSON.stringify(ContentData)
          }
        };
        for (let prop in this.required) {
          let propName = this.required[prop];
          if (ContentData[propName] === '') {
            this.turndownShow = true;
            this.turndownText = '请输入必填项';
            return false;
          }
        }
        this.loadingShow = true;
        if (this.$route.query.applyInfo !== undefined) {
          let query = JSON.parse(this.$route.query.applyInfo);
          if (query.IsReApply !== undefined) {
            postData.data.IsReApply = query.IsReApply;
          }
        }
        this.axios.post('/Process/Create', qs.stringify(postData))
        .then((res) => {
          if (res.data.IsSuccess === true) {
            this.loadingShow = false;
            this.changeDoneInfo(true, 'success', '提交申请成功', '你的申请已成功提交，等待上级领导审批中');
          } else {
            this.loadingShow = false;
            this.changeDoneInfo(true, 'warn', '提交申请失敗', `你的申请未能成功提交，具体错误：${res.data.ExMessage}`);
          }
        })
        .catch((err) => {
          this.loadingShow = false;
          this.changeDoneInfo(true, 'warn', '提交申请失敗', `你的申请未能成功提交，具体错误：${err}`);
        });
      },
      // 抄送人格式轉換 （只POST StaffNo）
      parseCopiers: function () {
        let copiers = this.$refs.makeCopy.resultList;
        let newCopiers = [];
        copiers.forEach((item) => {
          newCopiers.push({StaffNo: item.userid});
        });
        return newCopiers;
      },
      changeDoneInfo: function (status, iconType, title, msg) {
        this.doneIcon = iconType;
        this.doneTitle = title;
        this.doneMsg = msg;
        this.doneShow = status;
      },
      closeDoneInfo: function () {
        this.changeDoneInfo(false, '', '', '');
      },
      getDefaultMakeCopy: function () {
        return [
          // {
          //   userid: '10026',
          //   'name': 'Jacky Shek',
          //   'department': [2, 6, 12, 5],
          //   'position': '中原澳門及橫琴高級董事',
          //   'mobile': '98386138',
          //   'gender': 1,
          //   'email': '',
          //   'weixinid': null,
          //   'avatar': 'http://shp.qpic.cn/bizmp/j9Y9icaeLJ2Me8j5J5bHx5uRl8tevnxaMD2QNeWWhzNpj3LJltY5A9g/',
          //   'status': 1,
          //   'extattr': {
          //     'attrs': []
          //   },
          //   'checked': true,
          //   'removeSwitch': false
          // }
        ];
      },
      getReApplyMakeCopy: function (staffNoArr) {
        let postData = {
          data: {
            StaffNoArr: staffNoArr
          }
        };
        this.loadingShow = true;
        return this.axios.post('/Wechat/QueryUsersFromStaffNo', qs.stringify(postData))
        .then((res) => {
          this.loadingShow = false;
          if (res.data.IsSuccess === true) {
            this.makeCopyParams = this.makeCopyParams.concat(res.data.data.Users);
            this.$refs.makeCopy.resultList = this.makeCopyParams;
          } else {
            this.turndownShow = true;
            this.turndownText = '获取抄送人失败';
          }
        })
        .catch(() => {
          this.loadingShow = false;
          this.turndownShow = true;
          this.turndownText = '获取抄送人失败';
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  @import '../../assets/style/variable';
  .write-rebate {
    -webkit-overflow-scrolling: touch;
  }
</style>
